#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/types.h>

pid_t child1, child2;

void child1_handler(int sig)
{
    printf("Child process1 is killed by parent!\n");
    _exit(0); 
}

void child2_handler(int sig)
{
    printf("Child process2 is killed by parent!\n");
    _exit(0); 
}

void parent_handler(int sig)
{
    
    // 向子进程发送信号
    kill(child1, SIGUSR1);
    kill(child2, SIGUSR1);
    
    // 等待子进程结束
    int status;
    wait(&status);
    wait(&status);
    
    printf("Parent process is killed!\n");
    _exit(0); 
}

int main()
{
    // 父进程设置信号处理
    signal(SIGINT, parent_handler);
    
    // 创建第一个子进程
    child1 = fork();
    
    if (child1 == 0)
    {
        // 子进程1
        signal(SIGUSR1, child1_handler);
        while(1) {
            pause();
        }
    }
    
    // 创建第二个子进程
    child2 = fork();
    
    if (child2 == 0)
    {
        // 子进程2
        signal(SIGUSR1, child2_handler);
        while(1) {
            pause();
        }
    }
    
    printf("Parent process created two children:\n");
    printf("  Child1 PID: %d\n", child1);
    printf("  Child2 PID: %d\n", child2);
    printf("Press Ctrl+C to send signals to children...\n");
    
    // 父进程等待信号
    while(1)
    {
        pause();
    }
    
    return 0;
}
